package cn.edu.buaa.cnsatm.traffic_big_data_server.aviation.service;

import cn.edu.buaa.cnsatm.traffic_big_data_server.aviation.dao.AirportDAO;
import cn.edu.buaa.cnsatm.traffic_big_data_server.aviation.model.AirportWeatherModel;
import cn.edu.buaa.cnsatm.traffic_big_data_server.highway.dao.ImageDAO;
import cn.edu.buaa.cnsatm.traffic_big_data_server.util.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.activemq.artemis.api.core.Pair;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URLConnection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
public class AirportService {

    /**
     * @author: CHEN LI
     * @className: AirportService
     * @description: 航空气象影响
     * @data: 2019-10-19
     **/
    public static String getAirportWeatherEffects(String top_num){
        try{
            JsonArray ja = new JsonArray();
            ResultSet rs = AirportDAO.getAirportWeatherEffects(top_num);
            while(rs.next()) {
                JsonObject jo = new JsonObject();
                jo.addProperty("airport_name",rs.getString("airport_name"));
                jo.addProperty("effects",rs.getString("effects"));
                jo.addProperty("datetime",rs.getString("datetime"));
                ja.add(jo);
            }
            String  geoJsonStr = JsonArrayToGeoJsonUtil.toGeoJson(ja);
            rs.getStatement().close();
            rs.close();
            return geoJsonStr;
        }catch (SQLException e){
            e.printStackTrace();
            return null;
        }
    }

    public static String getAllAirportWeatherFromWebSaveToDatabase() throws SQLException, ParseException, FileNotFoundException, InterruptedException {
        /**
         * @author: LX
         * @methodName: getAllAirportWeatherFromWebSaveToDatabase
         * @description: 从http://airport.variflight.com/airport根据三字码获取机场天气信息以及受天气影响的状况
         * @data: 2019-10-24
         **/
        String airportWeatherSQLString = new String("-- 航空气象影响\n");
        final String AIRPORT_EFFECT_URL = "http://airport.variflight.com/airport/";//后接三字码
        /*LEFT与RIGHT之间要加四字码，后接时间*/
        final String AIRPORT_WEATHER_JSON_URL_LEFT  = "http://aviation.nmc.cn/json_data/simple/";
        final String AIRPORT_WEATHER_JSON_URL_RIGHT = ".json?t";
        int insertNum = 0;
        ResultSet resultSet = AirportDAO.getAllAirportCodeAndName();
        while (resultSet.next()){
            AirportWeatherModel airportWeather = new AirportWeatherModel();//建立机场气象对象
            String airportEffectURL = AIRPORT_EFFECT_URL + resultSet.getString("iata_code");
            /*先从第一个URL获取机场受天气影响的情况*/
            Document document = WebSpiderUtil.getHTMLDocument(airportEffectURL);
            String currentTime = DateUtil.getCurrentTime();
            airportWeather.setAirport_name(resultSet.getString("cn_name"));
            if(document == null){airportWeather.setEffects("未知");}
            else{
                Elements weatherEffect = document.getElementsByClass("ph-status");
                airportWeather.setEffects(weatherEffect.text());
            }

            /*获取机场气象详情*/
            String airportWeatherJsonURL = AIRPORT_WEATHER_JSON_URL_LEFT + resultSet.getString("gps_code") +
                    AIRPORT_WEATHER_JSON_URL_RIGHT + DateUtil.turnDateTimeToSecond(DateUtil.getCurrentTime());//拼接json地址的url
            JSONObject airportWeatherJson = JSON.parseObject(WebSpiderUtil.getJsonFromURL(airportWeatherJsonURL));
            if(airportWeatherJson != null){
                try{airportWeather.setCloud(airportWeatherJson.getString("txtCloudDesc"));}catch(NullPointerException e){}
                try{airportWeather.setWeather(airportWeatherJson.getString("weatherDesc"));}catch(NullPointerException e){}
                try{airportWeather.setTemperature(airportWeatherJson.getDouble("temperature"));}catch(NullPointerException e){}
                try{airportWeather.setWind_speed(airportWeatherJson.getDouble("windSpeed"));}catch(NullPointerException e){}
                try{airportWeather.setVisibility(airportWeatherJson.getDouble("visibility"));}catch(NullPointerException e){}
                try{airportWeather.setDatetime(airportWeatherJson.getString("time"));}catch(NullPointerException e){}
            }

            airportWeatherSQLString = airportWeatherSQLString + AirportDAO.insertAirportWeather(airportWeather) + "\n";
        }
        resultSet.getStatement().close();
        resultSet.close();
        return airportWeatherSQLString;
    }
    public static void getCloudImageFromWeb() throws ParseException, MalformedURLException, IOException {
        /**
         * @author: LX
         * @methodName: getCloudImageFromWeb
         * @description: 从http://pi.weather.com.cn爬取卫星云图，按照配置文件中的地址存储
         * @data: 2019-10-29
         **/
        final String CLOUD_IMAGE_URL_LEFT  = "http://pi.weather.com.cn/i/product/pic/l/sevp_nsmc_wxcl_asc_e99_achn_lno_py_";//20191027111500000
        final String CLOUD_IMAGE_URL_RIGHT = ".jpg";
        final int TIME_DIFFERENCE = 8;//卫星8小时时差
        String currentDateTime = DateUtil.getCurrentTime();//获取当前时间2019-10-28 11:11:11
        StringBuilder strBuilder = new StringBuilder(currentDateTime);
        strBuilder.setCharAt(14, '0');//将秒和分全部改为0
        strBuilder.setCharAt(15, '0');//将秒和分全部改为0
        strBuilder.setCharAt(17, '0');//将秒和分全部改为0
        strBuilder.setCharAt(18, '0');//将秒和分全部改为0
        String backDateTime = DateUtil.getDateTimeAfterSecond(String.valueOf(strBuilder), -24 * 60 * 60);
        currentDateTime = DateUtil.getDateTimeAfterSecond(String.valueOf(strBuilder), -8 * 60 * 60);
        System.out.println(backDateTime);
        /*将时间倒推24小时，每隔15分钟请求一个图，请求到了就存*/
        while(DateUtil.dateStringCompare(currentDateTime, backDateTime) == 1){//直到倒推的时间比当前时间晚，才停止
            backDateTime = DateUtil.getDateTimeAfterSecond(backDateTime, 15 * 60);
            String realDateTime = DateUtil.getDateTimeAfterSecond(backDateTime, 8 * 60 * 60);//获取8个小时之后的时间（卫星与北京时差）
            realDateTime = realDateTime.substring(0, 4) + realDateTime.substring(5, 7) +//删除-和空格:，作为文件名，不能有冒号
                    realDateTime.substring(8, 10) + realDateTime.substring(11, 13) + realDateTime.substring(14, 16);
            String delDateTime = backDateTime.substring(0, 4) + backDateTime.substring(5, 7) +//删除-和空格:，用于请求
                    backDateTime.substring(8, 10) + backDateTime.substring(11, 13) + backDateTime.substring(14, 16);
            String filename = PropertiesUtil.properties.getProperty("CLOUD_IMAGE_DIRECTORY") + realDateTime + ".jpg";  //下载路径及下载图片名称
            String cloudImageURL = CLOUD_IMAGE_URL_LEFT + delDateTime + "00000" + CLOUD_IMAGE_URL_RIGHT;
            WebSpiderUtil.saveImageFromWebToDir(cloudImageURL, filename);
            System.out.println("爬了一张气象云图");
            File _file = new File(filename);
            if(_file.length() < 2 * 10745){_file.delete();}//文件大小过小说明请求到了404页面，直接删掉
            else{
                ImageDAO.insertImage("cloud", PropertiesUtil.properties.getProperty("CLOUD_IMAGE_DIRECTORY"), realDateTime + ".jpg", DateUtil.getCurrentTime(), DateUtil.getDateTimeAfterSecond(backDateTime, 8 * 60 * 60));
            }
        }
    }
    public static void main(String args[]) throws SQLException, IOException, ParseException, InterruptedException {
        JDBCUtil.startConnection();
        //PropertiesUtil.setProperties();
        getCloudImageFromWeb();
        //JDBCUtil.startConnection();
        //getAllAirportWeatherFromWebSaveToDatabase();
    }
}

